package com.ibm.risk.irmp.base.auth.service.impl;

import com.ibm.risk.irmp.base.auth.dao.SystemPermissionRepository;
import com.ibm.risk.irmp.base.auth.dao.SystemRolePermissionRepository;
import com.ibm.risk.irmp.base.auth.dao.SystemRoleRepository;
import com.ibm.risk.irmp.base.auth.entity.SystemRole;
import com.ibm.risk.irmp.base.auth.entity.SystemRolePermission;
import com.ibm.risk.irmp.base.auth.service.IRoleManagementService;
import com.ibm.risk.irmp.common.exception.BusinessException;
import com.ibm.risk.irmp.common.utils.DaoUtils;
import jakarta.persistence.EntityManager;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(readOnly = false)
public class RoleManagementServiceImpl implements IRoleManagementService {
    private static final Logger log = LoggerFactory.getLogger(RoleManagementServiceImpl.class);
    @Autowired
    EntityManager entityManager;

    @Autowired
    SystemRoleRepository systemRoleRepository;

    @Autowired
    SystemRolePermissionRepository systemRolePermissionRepository;

    @Autowired
    SystemPermissionRepository systemPermissionRepository;

    @Autowired
    DaoUtils daoUtils;

    @Override
    @Transactional(readOnly = true)
    public List<SystemRole> getRoleList() {
        List<SystemRole> resultList = systemRoleRepository.findByIsActive(Boolean.TRUE);
        return resultList;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> showPermission(String pmsType) {
        String sql = "SELECT t.PMS_ID, t.PARENT_ID, t.PMS_NAME, t.PMS_STATUS\n" +
                "  FROM RI_BASE_AUTH_PERMISSION t\n" +
                "  WHERE t.PMS_TYPE = :pmsType and t.pms_status = 'T' \n" +
                "  ORDER BY t.PARENT_ID, t.SORT_ORDER";
//        Query query = entityManager.createNativeQuery(sql);
//        List<Map<String,Object>> resultList = query.setParameter("pmsType", pmsType)
//
//                //.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
//                .getResultList();
//        List<Map<String, Object>> resultListUpperCase = resultList.stream().map(x -> {
//            Map<String, Object> y = new HashMap<>();
//            x.forEach((k, v) -> y.put(k.toUpperCase(), v));
//            return y;
//        }).collect(Collectors.toList());

        Map<String, Object> params = new HashMap<>();
        params.put("pmsType", pmsType);
        List<Map<String, Object>> resultListUpperCase = daoUtils.pagedQuery(sql, 0, 1000, params);
        List<Map<String, Object>> groupTree = buildDataTree(resultListUpperCase, null);
        return groupTree;
    }

    private List<Map<String, Object>> buildDataTree(List<Map<String, Object>> dataList, Object pid) {
        //树形目录下拉框
        List<Map<String, Object>> params = new ArrayList<>();
        for (Map<String, Object> paramItem : dataList) {
            if (ObjectUtils.equals(pid, paramItem.get("PARENT_ID"))) {
                Map<String, Object> item = new HashMap<>();
                item.put("title", paramItem.get("PMS_NAME"));
                item.put("value", paramItem.get("PMS_ID"));
                item.put("key", paramItem.get("PMS_ID"));

                if (pid == null) {
                    item.put("expanded", true);
                } else {
                    item.put("expanded", false);
                }

                if ("F".equals(String.valueOf(paramItem.get("PMS_STATUS")))) {
                    item.put("disabled", true);
                }
                List<Map<String, Object>> children = new ArrayList<>();
                if (paramItem.get("PMS_ID") != null) {
                    children = buildDataTree(dataList, paramItem.get("PMS_ID"));
                }
                if (children.size() == 0) {
                    item.put("isLeaf", true);
                } else {
                    item.put("isLeaf", false);
                }
                item.put("children", children);
                params.add(item);
            }
        }
        return params;
    }

    @Override
    @Transactional(readOnly = true)
    public List<SystemRolePermission> showRolePermissions(String roleCode, String functionType) {
//        List<Long> IdList = new ArrayList<>();
        if (roleCode == null) {
            throw new BusinessException("请指定角色代码");
        }
        if (functionType == null) {
            throw new BusinessException("请指定功能或资源类型");
        }
        SystemRolePermission rolePermissionEntity = new SystemRolePermission();
        rolePermissionEntity.setRoleCode(roleCode);
        rolePermissionEntity.setDataType(functionType);
        List<SystemRolePermission> all = systemRolePermissionRepository.findAll(Example.of(rolePermissionEntity));
        return all;
    }

    @Override
    public void saveRole(SystemRole roleEntity) {
        SystemRole systemRoleEntity = null;
        if (roleEntity != null && roleEntity.getUpdate()) {
            //update
            Optional<SystemRole> roleOptional = systemRoleRepository.findById(roleEntity.getRoleCode());
            if (!roleOptional.isPresent()) {
                throw new BusinessException("指定的角色不存在");
            }
            systemRoleEntity = roleOptional.get();

            //不允许修改内置角色代码
            if (Boolean.TRUE.equals(systemRoleEntity.getIsBuildin()) && !systemRoleEntity.getRoleCode().equals(roleEntity.getRoleCode())) {
                throw new BusinessException("不允许修改系统内置角色代码");
            }
        } else {
            //add new
            systemRoleEntity = new SystemRole();

            systemRoleEntity.setIsBuildin(Boolean.FALSE);
        }
        systemRoleEntity.setRoleCode(roleEntity.getRoleCode());
        systemRoleEntity.setRoleName(roleEntity.getRoleName());
        systemRoleEntity.setIsActive(roleEntity.getIsActive());

        systemRoleRepository.save(systemRoleEntity);
    }


    @Override
    @Transactional
    public Boolean saveRolePermission(String roleCode, String functionType, List<Long> functionIds) {
        if (roleCode == null) {
            throw new BusinessException("请指定角色ID");
        }
        if (functionType == null) {
            throw new BusinessException("请指定功能/资源类型");
        }
        Optional<SystemRole> roleEntityOptional = systemRoleRepository.findById(roleCode);
        if (!roleEntityOptional.isPresent()) {
            throw new BusinessException("指定的角色不存在");
        }

        //读取数据库中现有记录
        SystemRolePermission rolePermissionEntity = new SystemRolePermission();
        rolePermissionEntity.setRoleCode(roleCode);
        rolePermissionEntity.setDataType(functionType);
        List<SystemRolePermission> savedRolePermissions = systemRolePermissionRepository.findAll(Example.of(rolePermissionEntity));

        List<Long> savedRolePermissionIds = new ArrayList<>();
        for (SystemRolePermission entity : savedRolePermissions) {
            if (functionIds.contains(entity.getPmsId())) {
                //保持不变
                savedRolePermissionIds.add(entity.getPmsId());
            } else {
                //删除
                systemRolePermissionRepository.deleteById(entity.getRolePmsId());
            }
        }
        ;

        //新增加数据记录
        functionIds.forEach(x -> {
            if (!savedRolePermissionIds.contains(x)) {
                //新增加记录
                SystemRolePermission entity = new SystemRolePermission();
                entity.setRoleCode(roleCode);
                entity.setPmsId(x);
                entity.setDataType(functionType);
                systemRolePermissionRepository.save(entity);
            }
        });
        return true;
    }

    @Override
    @Transactional(readOnly = true)
    public SystemRole findRoleById(String roleCode) {
        if (roleCode == null) {
            throw new BusinessException("请指定角色ID");
        }
        Optional<SystemRole> roleEntityOptional = systemRoleRepository.findById(roleCode);
        if (!roleEntityOptional.isPresent()) {
            throw new BusinessException("指定的角色不存在");
        }
        return roleEntityOptional.get();
//        Optional<SystemRole> middlewareRoleEntityOptional = systemRoleRepository.findOne(Example.of(roleEntity));
//        if(middlewareRoleEntityOptional.isPresent()){
//            return  middlewareRoleEntityOptional.get();
//        }
//        return null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(String roleCode) {
        if (roleCode == null) {
            throw new BusinessException("请指定角色代码");
        }
        Optional<SystemRole> roleEntityOptional = systemRoleRepository.findById(roleCode);
        if (!roleEntityOptional.isPresent()) {
            throw new BusinessException("指定的角色不存在");
        }

        SystemRole roleEntity = roleEntityOptional.get();
        if (Boolean.TRUE.equals(roleEntity.getIsBuildin())) {
            throw new BusinessException("不允许删除系统内置角色");
        }

        //删除角色
        systemRoleRepository.delete(roleEntity);

        //删除角色-权限关联数据
        systemRolePermissionRepository.deleteAllByRoleCode(roleEntity.getRoleCode());

        return true;
    }
}
